/*
 * @lc app=leetcode.cn id=108 lang=typescript
 *
 * [108] 将有序数组转换为二叉搜索树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function build(nums: number[], l: number, r: number): TreeNode | null {
  if (l > r) return null;
  const mid = (l + r) >> 1;
  // 用中间值创建root
  const root = new TreeNode(nums[mid]);
  // 递归处理左右子树
  root.left = build(nums, l, mid - 1);
  root.right = build(nums, mid + 1, r);
  return root;
}

function sortedArrayToBST(nums: number[]): TreeNode | null {
  return build(nums, 0, nums.length - 1);
}
// @lc code=end
